/*
 * @Author: 张笑天
 * @Date: 2018-03-07 17:10:22
 * @Last Modified by: lyuan2018
 * @Last Modified time: 2020-09-21 11:13:23
 */
import React from 'react';
import { routerShape } from 'react-router';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Modal, message, Button } from 'antd';
import {
  WeaTop,
  WeaTab,
  // WeaRightMenu,
  WeaErrorPage,
  WeaTools,
  WeaBrowser,
  WeaLocaleProvider,
} from 'ecCom';

import {
  listRoute,
  listParams,
  checkKeyinTab,
  checkTypeinTab,
  // checkChangeinTab,
  nameUpperCase,
} from '../util/index';
import { Todo } from './com';
import New from './New';
import View from './View';
import List from './List';
import ReadList from './view/ReadList';
import LabelNew from './emailSetting/label/Edit';
import FolderNew from './emailSetting/folder/Edit';
import AddContact from './emailContacts/AddContact';
import MenuWithLayout from './menu/MenuWithLayout';
import ImportEml from './list/ImportEml';
import * as MAILSET_APIS from '../apis/setting/mailSetting';
import EmailProgress from '../../../pc4backstage/email/public/emailProgress';
import Attachment from './Attachment';
import Contacts from './Contacts';
import * as EmailUtil from '../util/EmailUtil';

const getLabel = WeaLocaleProvider.getLabel;
const { confirm, warning } = Modal;
const { tryCatch } = WeaTools;

const displayModule = {
  new: New,
  view: View,
  list: List,
  attachment: Attachment,
  contacts: Contacts,
};

const store = [
  'routing',
  'emailMainStore',
  'emailNewStore',
  'emailOpsStore',
  'emailMenuStore',
  'emailPrintStore',
  'todoNewStore',
  'settingStore',
].concat(listRoute.map(l => `email${nameUpperCase(l)}Store`));

@tryCatch(
  React,
  props => (
    <WeaErrorPage
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_WeaErrorPage@2uv9em`}
      msg={
        props.error ||
        getLabel(186, '对不起，该页面异常，请联系管理员！', 'error')
      }
    />
  ),
  { error: '' },
)
@inject(...store)
@observer
class Main extends React.Component {
  static displayName = 'Main';
  static contextTypes = {
    router: routerShape,
  };
  constructor(props) {
    super(props);
    this.prefixClass = 'wea-email-main';
    const { href } = window.location;
    this.isSingle =
      href.indexOf('/spa/email/') > 0 || href.indexOf('/wui/') < 0;
    this.state = {
      visible: false,
      isSysAdmin: false,
      isExportDoc: false, // 确认导出目录Visible显隐
      docSetting: {}, // 文档信息
      editVisible: false, // 新建标签显隐
      xmlVisible: false, // 导出XML显隐
      operateid: '',
      leftMenuName: 'inbox',
      folderNewVisible: false,
    };
    this.searchParams = '';
  }
  componentDidMount() {
    const {
      location,
      route,
      emailMainStore,
      emailNewStore,
      emailOpsStore,
      emailMenuStore,
    } = this.props;
    const { router } = this.context;
    this.checkTheme();
    this.updateLocale();

    emailMainStore.getConfig().then((res) => {
      let userId = (res.userConfig && res.userConfig.userId) || '';
      if (userId === 1) this.setState({ isSysAdmin: true });
      else this.setState({ isSysAdmin: false });
      emailOpsStore.getEmailSize().then(() => {
        this.doTabAdd(location);
      });
    });

    // router.listen(location => {
    // });
    router.setRouteLeaveHook(route, ({ pathname }) => {
      // Warnning when go forward router out of main or 'main/email/monitor'
      const { tabInfo, canGoOut, setState } = emailMainStore;
      if (
        (pathname.indexOf('main/email') < 0 ||
          pathname === 'main/email/monitor') &&
        !canGoOut &&
        checkKeyinTab(tabInfo, 'new') &&
        emailNewStore.editing
      ) {
        confirm({
          content: getLabel(384188, '您有正在编写的邮件，确定离开？'),
          okText: getLabel(826, '确定'),
          onOk: () => {
            // Save to draft
            emailNewStore.clear();
            setState({ canGoOut: true });
            router.push(pathname);
          },
        });
        return false;
      }
    });

    emailMainStore.setState({ onOpenContact: this.onOpenContact });

    // 记录第一次进入邮件模块
    if (emailMenuStore.isNotWeiSearch) {
      emailMenuStore.setState({
        isNotWeiSearch: !(location.search.indexOf('subject=') > -1),
      });
    }
  }
  componentWillReceiveProps(nextProps) {
    const {
      location: { pathname, key },
      emailMainStore,
    } = this.props;
    const {
      location,
      location: { pathname: _pathname, key: k },
    } = nextProps;
    if (
      (pathname !== _pathname && _pathname.indexOf('main/email/') >= 0) ||
      (pathname === _pathname &&
        (pathname === 'main/email/new' ||
          pathname === 'main/email/tag' ||
          pathname === 'main/email/folder') &&
        key !== k)
    ) {
      // 此处解决（//邮件设置--阅读版式设置好之后，收件箱显示的阅读版式并不是设置的版式，刷新页面之后显示正常了）
      // 但是为啥要做判断，是防止点击邮件设置处菜单的时候，如果也走getconfig接口，会有执行条无法消失
      if (
        nextProps.location.pathname.startsWith('main/email/setting/') ||
        nextProps.location.pathname.startsWith('main/email/setting')
      ) {
        this.doTabAdd(location);
      } else {
        emailMainStore.getConfig().then((res) => {
          let userId = (res.userConfig && res.userConfig.userId) || '';
          if (userId === 1) this.setState({ isSysAdmin: true });
          else this.setState({ isSysAdmin: false });
          this.doTabAdd(location);
        });
        if (
          pathname === 'main/email/setting/mailSetting' &&
          emailMainStore.tabKey === 'list'
        ) {
          // let search = '"{' + this.searchParams.replace('?', '').replace(/&/gi, ',').replace(/=/gi,':') + '}"'
          emailMainStore.listSearch(nextProps);
        }
      }
    }

    this.checkTheme();
    this.updateLocale();
  }
  componentWillUnmount() {
    const { emailMainStore } = this.props;
    emailMainStore.clear();
    this.setState({ isSysAdmin: false });
  }
  checkTheme() {
    const theme = window.weaPortalTheme;
    const { href } = window.location;
    const { hasMenu: sg, setState } = this.props.emailMenuStore;
    const hasMenu = theme
      ? toJS(theme.store.portalThemeStore).themeInfo.themeLayoutType !== '1'
      : href.indexOf('/spa/email/') > 0 || href.indexOf('/wui/') < 0;
    /* eslint-disable */
    sg ^ hasMenu && setState({ hasMenu });
    /* eslint-enable */
  }
  // update locale
  updateLocale() {
    const {
      emailMainStore: { listTitle, setState, tabInfo: ti },
    } = this.props;
    const tabInfo = toJS(ti);
    const newLocale = {};
    const list = tabInfo.filter(tab => tab.tabKey === 'list')[0];
    const _17065 = getLabel(17065, '邮件列表');
    const locale = {
      inbox: getLabel('19816', '收件箱'),
      sent: getLabel('19558', '已发送'),
      draft: getLabel('2039', '草稿箱'),
      deleted: getLabel('2040', '垃圾箱'),
      doing: getLabel('83090', '待办邮件'),
      star: getLabel('81337', '标星邮件'),
      inner: getLabel('24714', '内部邮件'),
      folder: getLabel('30915', '我的文件夹'),
      tag: getLabel('81349', '我的标签'),
    };
    if (listTitle.inbox !== locale.inbox) {
      newLocale.listTitle = locale;
    }
    if (list.title.search(_17065) < 0) {
      newLocale.tabInfo = tabInfo.map((tab) => {
        if (tab.tabKey === 'list') {
          const mainTitle = locale[tab.route];
          const num = tab.title.match(/\s\(\d+\)/g);
          return {
            ...tab,
            title: `${_17065}${num ? num[0] : ''}`,
            mainTitle,
          };
        }
        return tab;
      });
    }
    Object.keys(newLocale).length > 0 && setState(newLocale);
  }
  // tab ops
  doTabAdd({ pathname, query, search, key }) {
    // const { router } = this.context;
    const {
      emailMainStore: {
        addTab,
        tabInfo: _tabInfo,
        setState,
        listTitle,
        viewStores,
      },
      emailNewStore: {
        clear,
        getInit,
        editing,
        sendingStatus,
        getSignList,
        getTemplateList,
        getHrmGroup,
        refreshTree,
      },
    } = this.props;
    const _path = pathname.replace('main/email/', '').split('/')[0];
    let tab = { route: _path, tabKey: _path, type: _path, query, search, key };
    if (_path === 'new') {
      tab.mainTitle = getLabel(81300, '写信');
      tab.title = getLabel(81300, '写信');
    } else if (listRoute.indexOf(_path) >= 0) {
      const t = listTitle[_path];
      tab = { ...tab, tabKey: 'list', type: 'list', mainTitle: t };
    } else if (_path === 'view') {
      let { id, title = getLabel(384187, '加载中...') } = query;
      const {
        baseInfo: { subjectText },
      } = viewStores[id] ? viewStores[id] : viewStores.init;
      title = subjectText && subjectText != '' ? subjectText : title;
      tab = {
        ...tab,
        tabKey: id,
        type: 'view',
        title,
        mainTitle: getLabel(384186, '查看邮件'),
      };
    } else if (_path === 'setting') {
      tab.mainTitle = getLabel(24751, '邮件设置');
      tab.title = getLabel(24751, '邮件设置');
    } else if (_path === 'contacts') {
      tab.mainTitle = getLabel(572, '联系人');
      tab.title = getLabel(572, '联系人');
    } else if (_path === 'attachment') {
      tab.mainTitle = getLabel(156, '附件');
      tab.title = getLabel(156, '附件');
    } else if (_path === 'monitor') {
      return;
      // tab.mainTitle = '邮件监控';
      // tab.title = '邮件监控';
    } else {
      return;
    }
    // diff query for new
    const tabInfo = toJS(_tabInfo);
    // const params = { ...query };
    // delete params.ontabchange;
    // const tabNew = checkChangeinTab(tabInfo, 'new', params);
    // if (pathname === 'main/email/new' && ((tabNew && !query.ontabchange))) {
    if (pathname === 'main/email/new' && !query.ontabchange) {
      const initNew = () => {
        clear();
        getInit(query);
        getSignList(query);
        getTemplateList(query);
        getHrmGroup();
        typeof refreshTree === 'function' && refreshTree();
      };
      if (sendingStatus !== '') {
        initNew();
      } else {
        const onOk = () => {
          initNew();
          setState({
            tabInfo: tabInfo.map(t => ({
              ...t,
              ...(t.tabKey === 'new' ? { query, search } : {}),
            })),
            tabKey: 'new',
          });
          // router.push(pathname + search);
        };
        editing
          ? confirm({
              content: getLabel(
                384171,
                '放弃正在编辑的邮件，并开始一封新的写信吗？',
              ),
              onOk,
              okText: getLabel(826, '确定'),
              onCancel: () => {
                setState({ tabKey: 'new' });
                // router.push(pathname + tabNew.search);
              },
            })
          : onOk();
      }
    }
    addTab(tab);
  }
  onTabEdit = (targetKey) => {
    const {
      emailMainStore: { delTab },
      emailNewStore,
      settingStore,
    } = this.props;
    const { router } = this.context;
    if (targetKey === 'setting') {
      settingStore.setStoreState({ selectedKey: '' });
      delTab(targetKey, router);
      return;
    }
    targetKey === 'new' && emailNewStore.editing
      ? confirm({
          content: getLabel(384172, '您有正在编写的邮件，确定关闭？'),
          okText: getLabel(826, '确定'),
          onOk: () => {
            // Save to draft
            emailNewStore.clear();
            delTab(targetKey, router);
          },
        })
      : delTab(targetKey, router);
  };
  onTabChange = (tabKey) => {
    const { router } = this.context;
    const { emailMainStore, emailNewStore } = this.props;
    const { tabInfo, setState } = emailMainStore;
    const tab = tabInfo.filter(t => t.tabKey === tabKey)[0];
    tab.type === 'view' && setState({ viewIdInTab: tabKey });
    const search =
      tabKey !== 'list' &&
      tabKey !== 'new' &&
      tabKey !== 'attachment' &&
      tabKey !== 'contacts'
        ? tab.search
        : !tab.search
        ? '?ontabchange=1'
        : tab.search.indexOf('ontabchange=1') > 0
        ? tab.search
        : `${tab.search}&ontabchange=1`;
    // 写信页面切换时，自动保存草稿响应
    if (tabKey === 'new') {
      emailNewStore.setState({ changeToNewPage: true });
    }
    router.push(`main/email/${tab.route}${search}`);
    this.searchParams = search;
    setState({ tabKey });
  };
  // ops
  refesh = (res, ids, closeViewInList, refeshOps) => {
    if (res.status === '1' || res.status === '1') {
      const {
        emailMainStore: { setState, tabInfo, viewStores, viewId, sortParams },
        emailMenuStore: { hasMenu, getMenu },
      } = this.props;
      const { query, route } = tabInfo.filter(t => t.tabKey === 'list')[0];
      const listStore = this.props[`email${nameUpperCase(route)}Store`];
      const {
        datas,
        form,
        pagination: { current },
      } = listStore;
      // refresh menu
      hasMenu && getMenu();
      // refresh list in store
      if (datas.length > 0) {
        const formParams = form.getFormParams();
        const params = {
          ...listParams[route],
          ...formParams,
          current,
          ...sortParams,
          ...query,
        };
        listStore
          .getDatas(params, ({ datas: _datas, total }) => {
            /* operate !== 'deletePermanently' && */ setState({
              tabInfo: tabInfo.map(t => ({
                ...t,
                title:
                  t.tabKey === 'list'
                    ? `${t.title.replace(/\s\(\d+\)/g, () => '')} (${total})`
                    : t.title,
              })),
            });
            setState({
              viewId:
                closeViewInList && _datas.map(d => d.id).indexOf(viewId) < 0
                  ? 'init'
                  : viewId,
            });
          })
          .setState({
            selectedRowKeys: [],
          });
        refeshOps && listStore.getdropDown(params);
      }
      // refresh view in store
      ids.forEach((mailId) => {
        // if (mailId === viewId || mailId === viewIdInTab) {
        const viewStore = viewStores[mailId];
        if (viewStore) {
          viewStore.getRight({ mailId }).then((data) => {
            data.viewRight === 1 &&
              viewStore.getBaseInfo({ mailId }).getDropDown({ mailId });
          });
        }
        // }
      });
    }
  };

  refreshList = () => {
    const {
      emailMainStore: { setState, tabInfo },
    } = this.props;
    const { query, route } = tabInfo.filter(t => t.tabKey === 'list')[0];
    const listStore = this.props[`email${nameUpperCase(route)}Store`];
    const {
      form,
      pagination: { current },
    } = listStore;
    // refresh list in store
    const formParams = form.getFormParams();
    const params = {
      ...listParams[route],
      ...formParams,
      current,
      ...query,
    };
    listStore
      .getDatas(params, ({ total }) => {
        setState({
          tabInfo: tabInfo.map(t => ({
            ...t,
            title:
              t.tabKey === 'list'
                ? `${t.title.replace(/\s\(\d+\)/g, () => '')} (${total})`
                : t.title,
          })),
        });
      })
      .setState({
        selectedRowKeys: [],
      });
  };
  onTagAddSuccess = (res) => {
    const { flag, status } = res;
    if (flag && status === '1') {
      // 新建并标记为
      const {
        emailMainStore: { waitTagAddedToSetIds },
      } = this.props;
      this.refesh(res, waitTagAddedToSetIds, false, true);
      this.setState({ editVisible: false });
    } else {
      message.error(getLabel(384180, '新建标签失败！'));
    }
  };
  onSetTag = async (ids, tagId, operation, refeshOps) => {
    if (tagId === 'createAndTagIt') {
      // Open the tag add in setting
      const {
        emailMainStore: { setState },
      } = this.props;
      this.refs.newLabel.wrappedInstance.addLabel(() =>
        this.setState({ editVisible: true }),
      );
      setState({ waitTagAddedToSetIds: ids });
    } else {
      const { emailOpsStore } = this.props;
      const res = await emailOpsStore.setTag({
        mailIds: `${ids}`,
        id: tagId,
        operation,
      });
      this.refesh(res, ids, false, refeshOps);
      return res;
    }
  };
  onCollect = async (ids, star) => {
    const { emailOpsStore } = this.props;
    const res = await emailOpsStore.setStar({ mailIds: `${ids}`, star });
    this.refesh(res, ids);
  };

  // 更新阅读状态
  onSetReadStatus = async (ids, status, type) => {
    const { emailOpsStore } = this.props;
    const res = await emailOpsStore.setReadStatus({
      mailIds: `${ids}`,
      status,
      type,
    });
    this.refesh(res, ids);
  };

  // 邮件识别发票
  emailOcrInvoice = async (params) => {
    const {
      emailMainStore: { emailOcrInvoice },
    } = this.props;
    const res = await emailOcrInvoice(params);
    this.refesh(res, [params.mailid]);
  };

  onDeleteEmail = async (ids, operate) => {
    const {
      emailMainStore: { delTab, tabKey },
      emailOpsStore,
    } = this.props;
    const { router } = this.context;
    const res = await emailOpsStore.deleteEmail({ mailIds: `${ids}`, operate });
    this.refesh(res, ids, true, '', operate);
    this.props.location.pathname === 'main/email/view' &&
      operate === 'deletePermanently' &&
      delTab(tabKey, router);
  };
  onFolderAddSuccess = ({ flag, id, status }) => {
    if (flag && status === '1') {
      const {
        emailMainStore: { waitFolderAddedToMoveIds },
      } = this.props;
      this.onMoveToFolder(waitFolderAddedToMoveIds, id, false, true);
    } else {
      // message.error(getLabel(384181, '新建文件夹失败！'));
    }
  };
  onMoveToFolder = async (ids, folderId, isIn, refeshOps) => {
    const {
      emailOpsStore: { moveToFolder },
    } = this.props;
    if (isIn) {
      warning({
        content: getLabel(
          384182,
          '邮件已经在您要移动的文件夹了，不能重复移动！',
        ),
      });
    } else if (folderId === 'createAndMoveTo') {
      // Open the folder add dialog in setting
      const {
        emailMainStore: { setState },
      } = this.props;
      setState({ waitFolderAddedToMoveIds: ids });
      this.setState({ folderNewVisible: true });
      if (!this.refs.newFolder) return;
      this.refs.newFolder.wrappedInstance.getData();
    } else {
      const res = await moveToFolder({
        mailIds: `${ids}`,
        folderId,
        operation: 'move',
      });
      this.refesh(res, ids, false, refeshOps);
      return res;
    }
  };
  clearSelectedRowKeys = () => {
    const {
      emailMainStore: { tabInfo },
    } = this.props;
    const { route } = tabInfo.filter(t => t.tabKey === 'list')[0];
    const listStore = this.props[`email${nameUpperCase(route)}Store`];
    listStore.setState({ selectedRowKeys: [] });
  };
  onDocSelected = (secId) => {
    if (!secId) {
      if (confirm({ content: getLabel(384183, '请选择文档目录！') })) {
        return;
      }
    }
    const {
      emailMainStore: { exportToDocIds },
      emailOpsStore: { exportToDoc },
    } = this.props;
    exportToDoc({ mailIds: `${exportToDocIds}`, secId });
    this.refs.doc.set();
    this.clearSelectedRowKeys();
  };
  onCustomerSelected = (crmIds) => {
    if (!crmIds) {
      if (confirm({ content: getLabel(506410, '请选择客户目录！') })) {
        return;
      }
    }
    const {
      emailMainStore: { exportToCrmIds },
      emailOpsStore: { exportToCrm },
    } = this.props;
    exportToCrm({ mailIds: `${exportToCrmIds}`, crmIds });
    this.clearSelectedRowKeys();
  };
  onExportToDoc = (ids) => {
    // 取常规设置里面的默认导出文档目录
    MAILSET_APIS.getUserMailSetting().then((data) => {
      const {
        emailMainStore: { setState },
      } = this.props;
      const { mailUserSetting } = data;
      let defaultSecId = mailUserSetting.secId;
      setState({ exportToDocIds: ids, defaultSecId });
      if (defaultSecId == '' || defaultSecId <= 0) {
        this.refs.doc.set();
        this.refs.doc.openModal();
        this.clearSelectedRowKeys();
      } else {
        this.setState({ docSetting: mailUserSetting, isExportDoc: true });
        // this.onExportToDocByDefId(defaultSecId,ids);
      }
    });
  };

  /* 打开新建联系人页面 */
  onOpenContact = () => {
    if (this.refs['main-addContact']) {
      this.refs['main-addContact'].wrappedInstance.addContacts();
    }
  };

  // 邮件打印
  onPrintEmail = (ids) => {
    const {
      emailPrintStore: { setPrintId },
    } = this.props;
    setPrintId(ids);
    const printurl =
      '/spa/email/static/index.html#/main/printemail/printemail?';
    const urlParams = `mailId=${ids}`;
    openFullWindowHaveBar(printurl + urlParams);
  };

  // 通过常规设置中的默认文档导出目录导出
  onExportToDocByDefId = (secId, ids) => {
    const {
      emailOpsStore: { exportToDoc },
    } = this.props;
    exportToDoc({ mailIds: ids, secId });
  };

  // 未设置常规设置中的默认文档导出目录导出
  onExportToCrm = (ids) => {
    this.refs.customer.openModal();
    const {
      emailMainStore: { setState },
    } = this.props;
    setState({ exportToCrmIds: ids });
  };

  onExportToEml = async (ids) => {
    const {
      emailOpsStore: { exportToEml },
    } = this.props;
    const res = await exportToEml({ mailIds: `${ids}` });
    const { emlexist, downloadUrl, msg, status } = res;
    if (status === '1') {
      if (emlexist) {
        window.open(downloadUrl);
        this.clearSelectedRowKeys();
      } else {
        confirm({ content: msg });
      }
    }
  };

  onExportToHtml = async (ids) => {
    const {
      emailOpsStore: { exportToHtml },
    } = this.props;
    const res = await exportToHtml({ mailIds: `${ids}` });
    const { downloadUrl, msg, status } = res;
    if (status === '1') {
      window.open(downloadUrl);
      this.clearSelectedRowKeys();
    } else {
      confirm({ content: msg });
    }
  };

  onImportEml = async (ids, leftMenuName, operateid) => {
    this.setState({ xmlVisible: true, leftMenuName, operateid });
  };

  onTodoClick = (todoSetIds, params = {}) => {
    const {
      emailMainStore: { setState },
      todoNewStore,
    } = this.props;
    setState({ todoSetVisible: true, todoSetIds });
    todoNewStore.getCondition(params);
  };
  onTodoComplete = async (mailIds) => {
    const {
      todoNewStore: { setTodoComplete },
      emailMenuStore,
    } = this.props;
    const res = await setTodoComplete({ mailIds: `${mailIds}` });
    this.refesh(res, mailIds);
    // 标准模式下刷新待办邮箱 数字
    if (!emailMenuStore.hasMenu) EmailUtil.updateMenuCount();
  };
  // get
  getRightMenu(isTop = false) {
    const {
      emailOpsStore: {
        emailSize: { occupyspace, totalspace },
        spaceRight,
      },
    } = this.props;
    // WeaProgress add border 2px, need width 100% -> 102%
    const btns = [];
    if (spaceRight === 1) {
      isTop &&
        btns.push(
          <div>
            <Button
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_Button@l6xi57@space`}
              type="primary"
              style={{ float: 'left' }}
              onClick={this.openMailSpace}
            >
              {getLabel(388540, '空间管理')}
            </Button>
          </div>,
        );
    }

    !this.state.isSysAdmin &&
      isTop &&
      btns.push(
        <span className={`${this.prefixClass}-capacity`}>
          <p>
            <EmailProgress
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_EmailProgress@lp7cs4@${occupyspace}`}
              percent={((occupyspace / totalspace) * 10000).toFixed(0) / 100}
              title={`${
                ((occupyspace / totalspace) * 10000).toFixed(0) / 100
              }%`}
              status={
                parseInt(
                  ((occupyspace / totalspace) * 10000).toFixed(0) / 100,
                ) >= parseInt(100)
                  ? 'exception'
                  : 'active'
              }
            />
          </p>
          <p>
            {getLabel(83111, '邮箱空间使用量')}
            {occupyspace}M/{totalspace}M
          </p>
        </span>,
      );

    return btns;
  }
  getTabInfo = datas =>
    datas.map(tab => ({
      ...tab,
      title: (
        <span className={`${this.prefixClass}-tabspan`}>
          {tab.type === 'new' ? (
            <i className="icon-coms-edit" style={{ marginRight: 5 }} />
          ) : tab.type === 'setting' ? (
            <i className="icon-email-Set-up" style={{ marginRight: 5 }} />
          ) : tab.type === 'attachment' ? (
            <i className="icon-email-Enclosure" style={{ marginRight: 5 }} />
          ) : tab.type === 'contacts' ? (
            <i className="icon-email-Contacts" style={{ marginRight: 5 }} />
          ) : null}
          {tab.title}
        </span>
      ),
      titleText: tab.title,
    }));

  getDisplayContent() {
    // 'new', 'list', 'view' not use router children
    const {
      location,
      children,
      emailMainStore: { viewIdInTab, tabInfo },
    } = this.props;
    const _path = location.pathname.replace('main/email/', '').split('/')[0];
    let arr = ['children', 'new', 'view'];
    // if (_path !== 'view') {  //此限制会导致list页面进入view时候，导致list被卸载，从而导致再次进入list时候，list需要重新初始化，引发刷新
    arr = [...arr, 'list', 'attachment', 'contacts']; // 此处为控制邮件tab列表的加载，在此处定义后，可在切换tab的时候，默认不卸载组件
    // }
    return arr.map((c) => {
      const isList = listRoute.indexOf(_path) >= 0;
      const isNormal = arr.indexOf(_path) < 0 && !isList && c === 'children';
      const display =
        c === _path || isNormal || (isList && c === 'list') ? 'block' : 'none';
      const Mod = checkTypeinTab(tabInfo, c) ? displayModule[c] : null;
      const props = {
        location,
        id: viewIdInTab,
        viewType: 'inTab',
        refesh: this.refesh,
        onSetTag: this.onSetTag,
        onCollect: this.onCollect,
        onSetReadStatus: this.onSetReadStatus,
        onDeleteEmail: this.onDeleteEmail,
        onMoveToFolder: this.onMoveToFolder,
        onTodoClick: this.onTodoClick,
        onTodoComplete: this.onTodoComplete,
        onExportToDoc: this.onExportToDoc,
        onExportToCrm: this.onExportToCrm,
        onExportToEml: this.onExportToEml,
        onExportToHtml: this.onExportToHtml,
        onImportEml: this.onImportEml,
        onPrintEmail: this.onPrintEmail,
        refreshList: this.refreshList,
        emailOcrInvoice: this.emailOcrInvoice,
        leftMenuName: _path,
      };
      return (
        <div
          className="email-right-content"
          style={{
            height: '100%',
            paddingBottom: 48,
            display,
            overflowY: 'auto',
          }}
        >
          {Mod ? (
            <Mod
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_Mod@ldj4yp@${props.id}`}
              {...props}
            />
          ) : isNormal ? (
            children
          ) : null}
        </div>
      );
    });
  }

  getModName(props) {
    const {
      location: { pathname },
    } = props || this.props;
    const _path = pathname.replace('main/email/', '').split('/')[0];
    // not use router to change module, need validate
    return listRoute.indexOf(_path) < 0 ? 'inbox' : _path;
  }
  getStoreNow = props =>
    this.props[`email${nameUpperCase(this.getModName(props))}Store`];

  onFolderCancel = () => this.setState({ folderNewVisible: false });

  onLableNewCancel = () => this.setState({ editVisible: false });

  onHandleAdd = () => {
    const {
      emailMainStore: { setState },
    } = this.props;
    setState({ addContactVisible: true });
  };
  onHandleCancel = () => {
    const {
      emailMainStore: { setState },
    } = this.props;
    setState({ addContactVisible: false });
  };
  onConfirmCancel = () => this.setState({ isExportDoc: false });
  onChangeDoc = () => {
    this.refs.doc.set();
    this.refs.doc.openModal();
    this.setState({ isExportDoc: false });
  };

  onImportEmlCancel = () => this.setState({ xmlVisible: false });
  onExportClick = () => {
    const {
      emailMainStore: { exportToDocIds, defaultSecId },
    } = this.props;
    this.onExportToDocByDefId(toJS(defaultSecId), toJS(exportToDocIds));
    this.clearSelectedRowKeys();
    this.setState({ isExportDoc: false });
  };

  getInMainContent() {
    const {
      emailMainStore,
      emailOpsStore,
      emailNewStore,
      location,
      settingStore,
    } = this.props;
    const { tableLoading } = this.getStoreNow(this.props);
    const {
      title,
      tabKey,
      tabInfo,
      addContactVisible,
      loading,
      waitTagAddedToSetIds,
    } = emailMainStore;
    const loadingNow =
      loading ||
      tableLoading ||
      emailOpsStore.loading ||
      emailNewStore.loading ||
      settingStore.loading;
    const tabs = this.getTabInfo(toJS(tabInfo));
    const { isExportDoc, docSetting } = this.state;
    const docTip =
      docSetting && docSetting.docRight
        ? docSetting.secMap &&
          `${getLabel('512946', '当前导出文档目录为：')}${
            docSetting && docSetting.secMap && docSetting.secMap.valueSpan
          }`
        : getLabel('512947', '当前导出文档目录无权限操作，请更换导出目录！');
    return [
      <WeaTop
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaTop@6fqp31@mainTop`}
        title={title}
        loading={loadingNow}
        icon={<i className="icon-coms-email" />}
        iconBgcolor="#788f9d"
        buttons={this.getRightMenu(true)}
        heightSpace={this.isSingle ? 0 : 10}
        buttonSpace={10}
        showDropIcon={false}
        dropMenuDatas={this.getRightMenu()}
      >
        <MenuWithLayout
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_MenuWithLayout@bp28t9@emaillayout`}
          location={location}
        >
          <WeaTab
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaTab@52qybv@showtab`}
            leftStyle={{ width: '100%' }}
            rightStyle={{ display: 'none' }}
            type="editable-inline"
            keyParam="tabKey"
            datas={tabs}
            selectedKey={tabKey}
            onChange={this.onTabChange}
            onEdit={this.onTabEdit}
          />
          {this.getDisplayContent()}
        </MenuWithLayout>
      </WeaTop>,
      <ReadList
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_ReadList@izrm8j@emailreadlist`}
      />,
      <Todo
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Todo@oj522b@emailtodo`}
        refesh={this.refesh}
      />,
      <LabelNew
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_LabelNew@0dxg50@emaillabel`}
        ref="newLabel"
        visible={this.state.editVisible}
        onCancel={this.onLableNewCancel}
        onSubmit={this.onTagAddSuccess}
        operation="labelCreate"
        mailIds={waitTagAddedToSetIds}
      />,
      <FolderNew
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_FolderNew@nh46eh@emailfolder`}
        ref="newFolder"
        title={getLabel(18475, '新建文件夹')}
        visible={this.state.folderNewVisible}
        onCancel={this.onFolderCancel}
        onSubmit={this.onFolderAddSuccess}
      />,
      <AddContact
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_AddContact@gwfcxb@emailaddcontact`}
        ref="main-addContact"
        visible={addContactVisible}
        onHandleAdd={this.onHandleAdd}
        onCancel={this.onHandleCancel}
        onSubmit={emailNewStore.getContactsTree}
      />,
      <WeaBrowser
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaBrowser@u8jd2r@emaildoccategory`}
        customized
        title={getLabel(84296, '选择文档目录')}
        type="doccategory"
        dataParams={{ iscreate: '1' }}
        ref="doc"
        onChange={this.onDocSelected}
      />,
      <WeaBrowser
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaBrowser@l4fj6x@emailcustomer`}
        customized
        title={getLabel(384185, '选择客户')}
        type="7"
        ref="customer"
        onChange={this.onCustomerSelected}
      />,
      <Modal
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Modal@f6kc8v@emailmesconfirm`}
        title={
          <div>
            <i
              className="icon-coms-Prompt"
              style={{
                color: '#faad14',
                fontSize: '20px',
                marginRight: 10,
                position: 'relative',
                top: 3,
              }}
            />
            {getLabel(131329, '信息确认')}
          </div>
        }
        visible={isExportDoc}
        centered
        bodyStyle={{ textAlign: 'center', padding: '30px 50px' }}
        onCancel={this.onConfirmCancel}
        footer={
          <div>
            <Button
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_Button@gfgphj@emailexport`}
              type="primary"
              disabled={docSetting && !docSetting.docRight}
              onClick={this.onExportClick}
            >
              {getLabel('17416', '导出')}
            </Button>
            <Button
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_Button@8rgias@emailchangedoc`}
              onClick={this.onChangeDoc}
            >
              {getLabel('512948', '更换目录')}
            </Button>
          </div>
        }
      >
        {docTip}
      </Modal>,
      <ImportEml
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_ImportEml@fm5001@emailimportEml`}
        visible={this.state.xmlVisible}
        onCancel={this.onImportEmlCancel}
        onResCancel={this.refreshList}
        leftMenuName={this.state.leftMenuName}
        operateid={this.state.operateid}
      />,
    ];
  }

  openMailSpace = () => {
    openFullWindowHaveBar(
      '/spa/email/static4engine/engine.html#/email/SpaceManage',
    );
  };

  render() {
    const { location, children } = this.props;
    const _path = location.pathname.replace('main/email/', '').split('/')[0];
    return (
      <div className={this.prefixClass} ref="main">
        {_path === 'monitor' ? children : this.getInMainContent()}
      </div>
    );
  }
}

export default Main;
